# -*- coding: utf-8 -*-

from selenium import webdriver
import time

isdo = 0
dian_count = 0
refresh_count = 0
liuyan_count = 0
dian_max = 500
refresh_timeout = 1
liuyan_max = 500
isscroll = 0
willdo = 0
nownum = 0
skip_persons = "洪鹏程"
en_liuyan = "Wonderful shooting"
login_no = ''
login_pw = ""
login_nm = "阿飞"
login_url = "https://hz.xzl.anjuke.com/zu/qianjiangxincheng/"
from tkinter import *
from wincener import center



def contain_zh(s):
    for c in s:
        if not('\u4e00' <= c <= '\u9fa5'):
            return False
    return True

driver = None
#driver = webdriver.Firefox()
def login():
    global driver,login_no,login_pw,login_url,isdo,skip_persons,dian_count
    driver.get(login_url)
    # time.sleep(2)
    # # driver.maximize_window()
    # now_handle = driver.current_window_handle
    # #查找点击列表，选择非列表作者清单，准备点击
    # list_item = driver.find_elements_by_class_name("list-item")
    # print('len_list:',len(list_item))
    # # now_handle = driver.current_window_handle
    # for icons in list_item:
    #     isdo = isdo + 1
    #     try:
    #         print(isdo, '元素:', icons)
    #         time.sleep(0.2)
    #         # driver.execute_script("arguments[0].scrollIntoView();", icons);
    #         time.sleep(0.2)
    #         button = icons.find_elements_by_tag_name("dd")
    #         print(isdo,'button姓名:',button[2].text)
    #         #item-title
    #         if button[2].text not in skip_persons:
    #             print('不在跳过列表，点击')
    #             dian_count = dian_count +1
    #             icons.find_element_by_class_name("item-title").click()
    #             # driver.implicitly_wait(6)
    #             # time.sleep(0.1)
    #             # 得到selenium打开的浏览器的所有句柄
    #             # all_hand = driver.window_handles
    #             # # 切换句柄
    #             # driver.switch_to_window(all_hand[-1])
    #             # driver.close()
    #             # all_hand = driver.window_handles
    #             # # 切换句柄
    #             # driver.switch_to_window(all_hand[-1])
    #             if dian_count%10==0:
    #                 handles = driver.window_handles
    #                 for handle in handles:
    #                     if handle != now_handle:
    #                         driver.switch_to_window(handle)
    #                         driver.close()
    #                         driver.switch_to_window(now_handle)
    #
    #         else:
    #             print('在跳过列表，不点击')
    #     except Exception as e:
    #         print('出现以下异常：')
    #         print ('str(Exception):\t', str(Exception))
    #         print ('str(e):\t\t', str(e))
    #         print ('repr(e):\t', repr(e))
    #         continue
    #     finally:
    #         print('异常后继续下一个')

    #点击完，等待间隔时间后刷新，再调用本函数--递归

    handles = driver.window_handles
    for handle in handles:
        if handle != now_handle:
            driver.switch_to_window(handle)
            driver.close()
            driver.switch_to_window(now_handle)

    time.sleep(refresh_timeout)
    login()



    # driver.find_element_by_css_selector("a.login").click()
    # #driver.maximize_window()  #将浏览器最大化显示
    # time.sleep(3)
    # driver.find_element_by_id("userName").send_keys(login_no)
    # driver.find_element_by_id("password").send_keys(login_pw)
    # driver.find_element_by_id("subButton").click()
    # time.sleep(1)
    # driver.find_element_by_css_selector("li._subscribeTab").click()
    # time.sleep(1)
    #driver.find_element_by_css_selector("a.v2_new_fav").click()

def doit():
    global driver, isdo, willdo, isscroll, dian_count, refresh_count, liuyan_count, dian_max, liuyan_max, skip_persons, en_liuyan
    # now_handle = driver.current_window_handle  # 获取当前窗口句柄
    # main_icons = driver.find_elements_by_class_name("new_icons_maincmp")
    # if isscroll > 0:
    #     main_icons = main_icons[isdo:]
    # print("len(main_icons):", len(main_icons))
    # isscroll = isscroll + 1
    while(1==1):
        time.sleep(4)
        driver.find_elements_by_xpath('// *[ @ id = "topOperatorMountNode"] / div / div[1] / div / label / span[1] / input').click()
        driver.find_elements_by_xpath('//*[@id="topOperatorMountNode"]/div/div[1]/div/button[3]').click()
        driver.find_elements_by_xpath('//*[@id="dialog-footer-' + "*" + '"]/span/button[1]').click()


        # isdo = isdo + 1
        # if isdo % 20 == 0:
        #     time.sleep(2)
        # try:
        #     time.sleep(0.2)
        #     # driver.execute_script("arguments[0].scrollIntoView();", icons);
        #     time.sleep(0.2)
        #     button = icons.find_element_by_class_name("v2_new_fav")
        #     fav_class = button.get_attribute("class")
        #     if "hearted" not in fav_class:
        #         if int(dian_max) > dian_count:
        #             button.click()  # 点赞
        #             print("点赞")
        #             dian_count = dian_count + 1
        #         else:
        #             print("点赞已达最大额度")
        #
        #     buttons = icons.find_elements_by_class_name("v2_new_zf")
        #     # print(buttons)
        #     for button in buttons:
        #         fav_class = button.get_attribute("class")
        #         if "hearted" not in fav_class:
        #             if int(refresh_timeout) > refresh_count:
        #                 # print("点击前")
        #                 # # time.sleep(3)
        #                 # print("点击")
        #
        #                 button.click()  # 转发
        #                 zfid = button.get_attribute("data-target")
        #
        #                 print('zfid', zfid)
        #
        #                 # ActionChains(driver).move_to_element(zfbut)
        #                 # driver.execute_script("$(arguments[0]).click()",button)
        #                 # button.click()
        #                 print("转发点击后")
        #                 # time.sleep(3)
        #                 # print(zfid)
        #                 # time.sleep(13)
        #                 dozf(driver, zfid, button)
        #             else:
        #                 print("转发已达最大额度")
        #
        #     if int(liuyan_max) > liuyan_count:
        #         liuyan_button = icons.find_element_by_class_name("commentTubiao")
        #         liuyan_button.click()  # 打开留言
        #         print("打开留言1")
        #         time.sleep(3)
        #         # 判断是否有俩窗口driver.window_handles
        #         ifgb = 0
        #         for handle in driver.window_handles:
        #             if handle != now_handle:
        #                 driver.switch_to_window(handle)
        #                 time.sleep(1)
        #                 ifgb = 1
        #                 driver.close()  # 关闭当前窗口
        #
        #         if ifgb == 1:
        #             driver.switch_to_window(now_handle)
        #             continue
        #         actors = driver.find_elements_by_class_name("actor")
        #         liuyan_flag = 0
        #         for actor in actors:
        #             # print(actor)
        #             # print(actor.text)
        #             if actor.text == 'hjy191':
        #                 liuyan_flag = 1
        #         print("liuyan_flag:" + str(liuyan_flag))
        #         if liuyan_flag == 1:
        #             close_but = driver.find_element_by_class_name("close")
        #             close_but.click()  # 关闭本留言
        #             continue
        #         liuyan_text = driver.find_element_by_class_name("new_comment")
        #         # //*[@id="user_show"]/div[12]/div/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div/div[2]/a
        #         photographer_info = driver.find_element_by_class_name("photographer_info")
        #         actor_name = photographer_info.find_element_by_class_name("actor")
        #         # print("actor_name:"+actor_name.text)
        #         if contain_zh(actor_name.text):
        #             liuyan_text.send_keys(skip_persons)
        #         else:
        #             liuyan_text.send_keys(en_liuyan)
        #         print("打开留言2")
        #         comment_icon = driver.find_element_by_class_name("comment_icon")
        #         comment_icon.click()
        #         print("打开留言3")
        #         close_but = driver.find_element_by_class_name("close")
        #         close_but.click()  # 关闭本留言
        #         liuyan_count = liuyan_count + 1
        #     else:
        #         print("留言已达最大额度")
        # except Exception as e:
        #     print('出现以下异常：')
        #     print ('str(Exception):\t', str(Exception))
        #     print ('str(e):\t\t', str(e))
        #     print ('repr(e):\t', repr(e))
        #     continue
        # finally:
        #     print('异常后继续下一个')


            # jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # print(len(jiahao_class))
            # for jiahao in jiahao_class:
            #     print(jiahao)
            #     jiahao.click()
            #     print("加号点击了")
            #     jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # comfirmZf = driver.find_element_by_css_selector("comfirmZf")
            # # comfirmZf.click()
            # print("确认转发")

def dozf(driver,zfid):
    parentitem = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "inside"]')
    for pitem in parentitem:
        itemList = pitem.find_elements_by_xpath('//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')
    # itemList = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')
    # webuiPopover60 > div.webui-popover-inner > div > div > div > div > div.inside > div:nth-child(1) > div.jiaohao
        print(len(itemList))
        if len(itemList) == 0:
            driver.find_element_by_xpath('//div[@id = "'+zfid+'"]//span').click()
            return True
        else:
            print(len(itemList))
            i = 1
            jiahao = itemList[0]
            jiahao.click()
            print("加号点击了")
    time.sleep(1)
    dozf(driver,zfid)

def ifcomment(driver,nich):
    button1s = driver.find_elements_by_class_name("actor")
    for button in button1s:
        fav_class = button.get_attribute("href")
        if nich in fav_class:
            return False
    return True
# #评论
# buttons = driver.find_elements_by_class_name("commentTubiao")
# for button in buttons:
#     # print(button)
#     fav_class = button.get_attribute("class")
#     # print(fav_class)
#     if "notisGroup" not in fav_class:
#         print("单击评论")
#         button.click()  # 评论
#         time.sleep(1)
#         if ifcomment(driver,"hjy191"):
#             print("评论")
#         driver.find_element_by_css_selector("div.close").click()
#     time.sleep(1)

'''
print (len(buttons))
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(1)
buttons = driver.find_elements_by_class_name("v2_new_fav")
print (len(buttons))
'''

import threading
def fun():
    th=threading.Thread(target=dopx,args=())
    th.setDaemon(True)#守护线程
    th.start()


def dopx():
    # login()
    # while True:
    global driver
    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    try:
        login()#driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    except ValueError:
        print('str(Exception):\t')
    finally:
        time.sleep(5)

root = Tk()
label1 = Label(root,text='0')
label2 = Label(root,text='0')
label3 = Label(root,text='0')

def threadGetCount():
    global label1
    while(True):
        label1['text'] = '累计点击量:'+str(getPrice())
        label2['text'] = '累计刷新量:'+str(getZhuanfa())
        # label3['text'] = '累计留言数:'+str(getLiuyan())
        time.sleep(1)

def getPrice():
    global dian_count
    return dian_count
def getZhuanfa():
    global refresh_count
    return refresh_count
# def getLiuyan():
#     global liuyan_count
#     return liuyan_count




#driver.quit()
if __name__=='__main__':
    import datetime

    # global root
    # root.maxsize(600, 400)
    root.minsize(300, 240)
    end_date = datetime.datetime.strptime("2018-10-14", "%Y-%m-%d")
    datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
    begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
    print(end_date)
    print(datetimenowTime)
    print(begin_date)
    if begin_date < end_date:
        date_time1 = end_date.strftime("%Y-%m-%d")
        war = '截止到'+date_time1+'如有问题联系qq:494514014'
        print(war)
        root.title(u"点击自动化工具")
        label = Label(root, bg='yellow', height=3,wraplength=320,  justify='left')
        label['text'] = u'试用版-'+war
        label.pack()
        Button(root, text='启动浏览器', command=fun).pack()
        Button(root, text='循环删除', command=doit).pack()
        label1.pack()
        label2.pack()
        # label3.pack()

        frame = Frame(root)
        frame.pack()
        # lab1 = Label(frame, text="点击限额:")
        # lab1.grid(row=0, column=0, sticky=W)
        # ent1 = Entry(frame)
        # ent1.grid(row=0, column=1, sticky=W)
        # ent1.insert(10, dian_max)
        lab2 = Label(frame, text="刷新间隔（秒）:")
        lab2.grid(row=1, column=0)
        ent2 = Entry(frame)
        ent2.insert(10, refresh_timeout)
        ent2.grid(row=1, column=1, sticky=W)
        lab3 = Label(frame, text="安居客目标网址:")
        lab3.grid(row=2, column=0)
        ent3 = Entry(frame)
        ent3.insert(10, login_url)
        ent3.grid(row=2, column=1, sticky=W)
        lab4 = Label(frame, text="跳过发布人列表:")
        lab4.grid(row=3, column=0)
        ent4 = Entry(frame)
        ent4.insert(10, skip_persons)
        ent4.grid(row=3, column=1, sticky=W)
        # lab5 = Label(frame, text="英文留言内容:")
        # lab5.grid(row=4, column=0)
        # ent5 = Entry(frame)
        # ent5.insert(10, en_liuyan)
        # ent5.grid(row=4, column=1, sticky=W)
        # lab6 = Label(frame, text="登录手机号:")
        # lab6.grid(row=5, column=0)
        # ent6 = Entry(frame)
        # ent6.insert(10, login_no)
        # ent6.grid(row=5, column=1, sticky=W)
        # lab7 = Label(frame, text="登录密码:")
        # lab7.grid(row=6, column=0)
        # ent7 = Entry(frame,show='*')
        # ent7.insert(10, login_pw)
        # ent7.grid(row=6, column=1, sticky=W)
        # lab8 = Label(frame, text="昵称:")
        # lab8.grid(row=7, column=0)
        # ent8 = Entry(frame)
        # ent8.insert(10, login_nm)
        # ent8.grid(row=7, column=1, sticky=W)
        def Submit():
            global liuyan_max, dian_max,refresh_timeout,skip_persons,en_liuyan,login_no,login_pw,login_url
            # dian_max= ent1.get()
            refresh_timeout = ent2.get()
            # liuyan_max = ent3.get()
            skip_persons = ent4.get()
            login_url = ent3.get()
            # en_liuyan = ent5.get()
            # login_no = ent6.get()
            # login_pw = ent7.get()
            # login_nm = ent8.get()
        button = Button(frame, text="保存配置", command=Submit)
        button.grid(row=7, column=1, sticky=E)



        
        center(root)
        t = threading.Thread(target=threadGetCount, args=(), name='thread-refresh')
        t.setDaemon(True)
        t.start()
        root.mainloop()
        # dopx()
    else:
        print('不能用')
        from tkinter import *

        root.title("提醒")
        label = Label(root)
        label['text'] = u'试用期已过，请联系 guocdfeifei@163.com 获取更新或旺旺guocdfeifei'
        label.pack()
        center(root)
        root.mainloop()

